package com.google.developers.tv.gdl;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

public class LoadingActivity extends Activity {

  ProgressBar bar;
  private int loadingStatus = 0;
  private long startStamp = 0;
  private Handler loadingBarHandler = new Handler();
  private Context myContext;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startStamp = System.currentTimeMillis();
    
    

    // Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    // Remove notification bar
    this.getWindow().setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_loading);
    
    initializeWidgets();

  }

  public void initializeWidgets() {

    final ProgressBar bar = (ProgressBar) findViewById(R.id.loadingProgressBar);
    
    bar.setProgress(0);
    bar.setMax(100);
    
    new Thread(new Runnable(){
      @Override
      public void run() {
        while(loadingStatus < 100) {
          loadingStatus = doLoadingTask();
          
          loadingBarHandler.post(new Runnable() {
            @Override
            public void run() {
              bar.setProgress(loadingStatus);
              if (loadingStatus >= 100) {
//                doNotifyByToast("Done Initializing App...");
                // load the dashboard activity
                Intent myIntent = new Intent(bar.getContext(), DashboardActivity.class);
                startActivityForResult(myIntent, 0);
              }
            }
          });
        }
      }}).start();
  }
  
  public void doNotifyByToast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
  }
  
  public int doLoadingTask() {
    long deltaStamp = System.currentTimeMillis() - startStamp;
    if (deltaStamp < 1000) {
      return 10;
    } else if (deltaStamp < 2000) {
      return 20;
    } else if (deltaStamp < 3000) {
      return 30;
    } else if (deltaStamp < 4000) {
      return 40;
    } else if (deltaStamp < 5000) {
      return 50;
    } else if (deltaStamp < 6000) {
      return 60;
    } else if (deltaStamp < 7000) {
      return 70;
    } else if (deltaStamp < 8000) {
      return 80;
    } else if (deltaStamp < 9000) {
      return 90;
    } else if (deltaStamp < 10000) {
      return 100;
    }
    return 0;
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_loading, menu);
    return true;
  }
}
